package com.px.web.controller.system;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson2.JSONObject;
import com.px.common.constant.Constants;
import com.px.common.core.domain.AjaxResult;
import com.px.common.core.domain.entity.SysMenu;
import com.px.common.core.domain.entity.SysRole;
import com.px.common.core.domain.entity.SysUser;
import com.px.common.core.domain.model.LoginBody;
import com.px.common.utils.SecurityUtils;
import com.px.framework.aes.AesSecurityParameter;
import com.px.framework.web.service.SysLoginService;
import com.px.framework.web.service.SysPermissionService;
import com.px.system.service.ISysMenuService;
import com.px.system.service.ISysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author WRJ
 */
@Slf4j
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysRoleService roleService;

    @Value("${mqtt.host}")
    private String mqttHost;

    @Value("${mqtt.username}")
    private String mqttUsername;

    @Value("${mqtt.password}")
    private String mqttPassword;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取mqtt
     *
     * @return 结果
     */
    @GetMapping("/getMqtt")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult getMqtt()
    {
        JSONObject jb = new JSONObject();
        jb.put("mqttHost",mqttHost);
        jb.put("mqttUsername",mqttUsername);
        jb.put("mqttPassword",mqttPassword);
        return AjaxResult.success(jb);
    }


    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if(roles.contains("admin")){
            permissions.add("*:*:*");
        }
        // 将角色首页类型求和, 然后与3比对, 超过3的按3处理,否则取原值
        int sum = roleService.selectRolesByUserIdWithOutDataScope(user.getUserId())
                .stream().filter(r -> null != r.getIndexType()).mapToInt(SysRole::getIndexType).distinct().sum();

        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("indexType", NumberUtil.min(sum, 3));
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
